package com.csaba.connector.web.util;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;

import com.csaba.util.LoggerHelper;

public class SpecialHttpClient extends DefaultHttpClient
{
	public final static String CERT_OTP = "otp_keystore";
	public final static String CERT_VERISIGN = "verisign_keystore";
	public final static String CERT_NETLOCK_B = "netlockclassb";
	public final static String CERT_NETLOCK_A = "netlockclassa";
	public final static String CERT_NETLOCK_ARANY_B = "netlock_arany_classb";
	public final static String CERT_ALL = "ALL";

	private final static Logger logger = LoggerHelper.getDefaultLogger();

	private final String certType;

	public SpecialHttpClient( final String certType )
	{
		super();
		this.certType = certType;
		logger.info("Connection is going to use (keystore): " + certType);
	}

	@Override
	protected ClientConnectionManager createClientConnectionManager()
	{
		final SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", newSslSocketFactory(), 443));
		return new SingleClientConnManager(getParams(), registry);
	}

	private SSLSocketFactory newSslSocketFactory()
	{
		try
		{
			String fileName = certType;
			if ( System.getProperty("java.vendor").contains("Android") )
				fileName = certType + ".bks";

			final InputStream stream = VerisignCertificate.class.getResourceAsStream(fileName);
			final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
			try
			{
				ks.load(stream, "changeit".toCharArray());
			}
			finally
			{
				stream.close();
			}

			final SSLSocketFactory sf = new AdditionalKeyStoresSSLSocketFactory(ks);
			//sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
			return sf;
		}
		catch ( final Exception e )
		{
			logger.log(Level.SEVERE, "Failed to initialize HttpClient.", e);
			throw new IllegalStateException("Failed to initialize HttpClient.", e);
		}
	}

}
